package com.fingard.dsp.bank.directbank.gac01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * @author Parker on 2020-06-18.
 * @version 1.0
 */
public class GAC01SinglePay extends GAC01Base implements ISinglePay {
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        return d_1908_SglPay_1(p_req1908);
    }

    private RetAtsSingle d_1908_SglPay_1(ReqSingle p_req1908) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail detail = new RetAtsSglDetail();
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter);
            xmlWriter.writeStartElement("Iss_Itreasury");
            xmlWriter.writeStartElement("InstrReq");
            xmlWriter.writeElementString("OperationType", "1");//操作类型
            xmlWriter.writeElementString("SystemID", bankFront.termid);//系统ID
            xmlWriter.writeElementString("BatchNo", "");//批次号
            xmlWriter.writeElementString("BatchNum", "");//批次比数
            xmlWriter.writeStartElement("InstrContent");
            xmlWriter.writeElementString("ApplyCode", p_req1908.singleDetail.askNumber);//业务申请编号
            if ("1".equals(p_req1908.singleDetail.sameBnk)) {
                xmlWriter.writeElementString("TransType", "NBZZ");//交易类型 YHFK：银行付款NBZZ：内部转账，
            } else {
                xmlWriter.writeElementString("TransType", "YHFK");//交易类型 YHFK：银行付款NBZZ：内部转账，
            }
            xmlWriter.writeElementString("Amount", p_req1908.singleDetail.payAmount);//金额
            xmlWriter.writeElementString("ExcuteDate", DateHelper.convertD8toD10(p_req1908.singleDetail.payDate));//执行日
            xmlWriter.writeElementString("ClientCode", bankFront.org);//客户编号
            xmlWriter.writeElementString("PayerAcctNo", p_req1908.singleDetail.payAct);//付款方账户编号
            xmlWriter.writeElementString("PayeeAcctNo", p_req1908.singleDetail.recAct);//收款方账户号
            xmlWriter.writeElementString("PayeeAcctName", p_req1908.singleDetail.recName);//收款方账户名称
            xmlWriter.writeElementString("RemitBankName", p_req1908.singleDetail.cnapsName);//收款方的汇入行名称
            xmlWriter.writeElementString("RemitBankCNAPS", p_req1908.singleDetail.cnapsCode);//收款方的汇入行联行号
            xmlWriter.writeElementString("RemitProvince", p_req1908.singleDetail.getOppProvinceAndCity()[0]);//收款方汇入省
            xmlWriter.writeElementString("RemitCity", p_req1908.singleDetail.getOppProvinceAndCity()[1]);//收款方汇入市
            xmlWriter.writeElementString("ConfirmUser", bankFront.operator);//提交人
            xmlWriter.writeElementString("ConfirmTime", Format.DateTimeFormat.format(p_req1908.singleDetail.getPayDateTime()));//提交时间
            xmlWriter.writeElementString("Note", p_req1908.singleDetail.abstractATS);//摘要
            xmlWriter.writeElementString("Purpose", p_req1908.singleDetail.purpose);//用途
            xmlWriter.writeElementString("Appertain", p_req1908.singleDetail.memo);//附言
            xmlWriter.writeEndDocument();

            String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString(), p_req1908.reqHeader.transType, p_req1908.reqHeader.transType);
            if (tmpRetBkStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    detail.respCode = "0";
                    detail.reqSeqID = p_req1908.singleDetail.askNumber;
                    detail.respInfo = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/InstrRen/RenContent/StatusDec");
                    if (StringHelper.isNullOrEmpty(detail.respInfo)) {
                        detail.respInfo = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/InstrRen/BatchStatusDec");
                    }
                    detail.transState = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/InstrRen/RenContent/StatusNo");
                    if (StringHelper.isNullOrEmpty(detail.transState)) {
                        detail.transState = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/InstrRen/BatchStatusNo");
                    }
                    detail.payInfoCode = detail.transState;
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpRetBkStr[0].equals(ConnState.FAIL)) {
                detail.respCode = "0";
                detail.respInfo = tmpRetBkStr[1];
                detail.reqSeqID = p_req1908.singleDetail.askNumber;
                detail.transState = PaymentState.FAIL_Payment;
                detail.payInfoCode = tmpRetBkStr[0];
            } else {
                detail.respCode = "-1";
                detail.respInfo = tmpRetBkStr[1];
                detail.reqSeqID = p_req1908.singleDetail.askNumber;
            }
        } catch (Exception e) {
            detail.respCode = "-1";
            detail.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRetDetail(detail);
        return retAts;
    }

    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        return d_1944_QrySglPay_2(p_req1944);
    }

    private RetAtsSingle d_1944_QrySglPay_2(ReqQrySingle p_req1944) throws Exception {
        RetAtsSingle retAtsSingle = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail detail = new RetAtsSglDetail();
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter);
            xmlWriter.writeStartElement("Iss_Itreasury");
            xmlWriter.writeStartElement("QueryReq");
            xmlWriter.writeElementString("OperationType", "2");//操作类型
            xmlWriter.writeElementString("SystemID", bankFront.termid);//系统ID
            xmlWriter.writeElementString("BatchNo", "");//批次号
            xmlWriter.writeStartElement("QueryContent");
            xmlWriter.writeElementString("ApplyCode", p_req1944.askNumber);//业务申请编号
            xmlWriter.writeElementString("ExcuteDate", Format.Date10Format.format(p_req1944.getBgnDateTime()));//日期
            xmlWriter.writeEndDocument();

            String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString(), p_req1944.reqHeader.transType, p_req1944.reqHeader.transType);
            if (tmpRetBkStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    //若查询过程中出现异常信息返回如下响应包格式
                    //<?xml version="1.0" encoding = "GBK"?>
                    //	<Iss_Itreasury>
                    //		<InstrRen>
                    //			<OperationType>操作类型</OperationType>
                    //			<RenContent>
                    //				<ApplyCode>-1</ApplyCode>
                    //				<StatusNo>01</StatusNo>
                    //				<StatusDec>异常描述</StatusDec>
                    //			</RenContent>
                    //		</InstrRen>
                    //	</Iss_Itreasury>
                    //01:失败；接收或处理失败（单笔和批量失败都用此状态码，仅代表指令接收状态）
                    detail.respCode = "0";
                    String applyCode = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/InstrRen/RenContent/ApplyCode");
                    String statusNo = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/InstrRen/RenContent/StatusNo");
                    if ("-1".equals(applyCode) && "01".equals(statusNo)) {
                        detail.respInfo = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/InstrRen/RenContent/StatusDec");
                        detail.transState = statusNo;
                        detail.payInfoCode = detail.transState;
                    } else {
                        detail.respInfo = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/QueryRen/RenContent/StatusDec");
                        if (StringHelper.isNullOrEmpty(detail.respInfo)) {
                            detail.respInfo = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/QueryRen/BatchStatusDec");
                        }
                        detail.transState = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/QueryRen/RenContent/StatusNo");
                        if (StringHelper.isNullOrEmpty(detail.transState)) {
                            detail.transState = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/QueryRen/BatchStatusNo");
                        }
                        detail.payInfoCode = detail.transState;
                    }
                    detail.reqSeqID = p_req1944.askNumber;
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpSbMsg.toString();
                }
            } else {
                detail.respCode = "-1";
                detail.respInfo = tmpRetBkStr[1];
            }
        } catch (Exception e) {
            detail.respCode = "-1";
            detail.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAtsSingle.writeRetDetail(detail);
        return retAtsSingle;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
